const App = getApp()
var amapFile = require('../../utils/amap-wx.js')
Page({
  data: {
    msgList: [],
    mapheight: '',
    longitude: '',
    latitude: '',
    addressDetail: '',
    points: [],
    polyline: [],
    markers: [],
    ask: '',
    hidden: 1,
    array: ['已加', '不想加了'], //取消订单
    index: '',
    detail: '',
    scale: 14,
    setInter: '', //定时器
    pageShow: false
  },
  onLoad: function (options) {
    let that = this
    var myAmapFun = new amapFile.AMapWX({
      key: 'f8b1262c6afbe526f37c449e593ea859'
    });
    myAmapFun.getRegeo({
      success: function (data) {
        console.log(data)
        that.setData({
          addressDetail: data[0].desc,
          latitude: data[0].latitude,
          longitude: data[0].longitude,
        })
        let address = {
          detail: data[0].desc,
          latitude: data[0].latitude,
          longitude: data[0].longitude
        }
        wx.setStorageSync('address', address)
      },
      fail: function (info) {}
    })
    that.reason()
    that.news()
  },
  reason(){
    let that=this
    App.api.$http({
      url: 'index/getreason',
      method: 'get',
      data: {}
    }, {}).then(res => {
      if (res) {
        that.setData({
          array: res.data.reason
        })
      }
    })
  },
  onShow: function () {
    let that = this
    let ask = wx.getStorageSync('ask')
    that.setData({
      ask: ask
    })
    // 获取缓存地址
    let address = wx.getStorageSync('address')
    if (address != '') {
      that.setData({
        addressDetail: address.detail,
        latitude: address.latitude,
        longitude: address.longitude,
      })
    } else {
      that.getLocation()
    }
    if (that.data.longitude != '') {
      that.index()
    }
    let userid = wx.getStorageSync('user_id')
    if (userid) {
      that.order()
    }
    that.mapheight()
  },

  // 获取首页滚动加油信息列表
  news() {
    let that = this
    App.api.$http({
      url: 'index/getRecord',
      method: 'POST',
      data: {}
    }, {}).then(res => {
      if (res) {
        that.setData({
          pageShow: true,
          msgList: res.data.record
        })
      }
    })
  },

  getLocation() {
    console.log('获取定位')
    let that = this
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        wx.setStorageSync('sh_oil_user_pre', true)
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        let address = {
          latitude: res.latitude,
          longitude: res.longitude
        }
        // that.analysisTap(res.latitude, res.longitude)
        wx.setStorageSync('address', address)
        that.index()
      },
      fail() {
        wx.setStorageSync('sh_oil_user_pre', false)
        wx.navigateTo({
          url: '/pages/nomap/nomap',
        })
      }
    })
  },

  // 获取订单信息
  async order() {
    let that = this
    await App.api.$http({
      url: 'Oilorder/noworder',
      method: 'POST',
      data: {
        lat: that.data.latitude,
        lng: that.data.longitude
      }
    }, {}).then(res => {
      if (res) {
        that.new()
        let orderdata = res.data.order
        that.setData({
          hidden: 2,
          order: res.data.order
        })
        that.mapheight()
        let markers = that.data.markers
        markers.push({
          id: 0,
          longitude: Number(orderdata.longitude),
          latitude: Number(orderdata.latitude),
          iconPath: '/img/start.png',
          width: 32,
          height: 32,
          callout: {
            content: '加油位置',
            color: '#fff',
            fontSize: 12,
            borderRadius: 6,
            display: 'ALWAYS',
            bgColor: '#6F8AA5',
            padding: '5',
          }
        }, {
          id: 1,
          longitude: Number(orderdata.staff.longitude),
          latitude: Number(orderdata.staff.latitude),
          iconPath: '/img/car.png',
          width: 40,
          height: 40,
          callout: {
            content: '',
            color: '#fff',
            fontSize: 12,
            borderRadius: 6,
            display: 'ALWAYS',
            bgColor: '#6F8AA5',
            padding: '5',
          }
        });

        console.log(that.data.markers)
        that.setData({
          markers: markers,
          points: markers
        })
        that.getDistance()
        // 定时获取司机位置
        // that.car()
      } else {
        that.setData({
          markers: [],
          hidden: 1
        })
        that.mapheight()
      }
    })
  },
  new() {
    let that = this
    that.setData({
      markers: []
    })
    that.data.setInter = setInterval(
      function () {
        that.order()
        clearInterval(that.data.setInter)
      }, 20000);
  },
  // 获取首页信息
  index() {
    let that = this
    App.api.$http({
      url: 'Index/index',
      method: 'GET',
      data: {
        latitude: that.data.latitude,
        longitude: that.data.longitude
      }
    }, {}).then(res => {
      if (res) {
        that.setData({
          detail: res.data.setting,
          is_support: res.data.is_support
        })
        //增加如果是司机需要跳转到司机端个人中心
        if(res.data.user.isstaff==1){
          // wx.redirectTo({
          //   url: '/pages/car/home/home',
          // })
        }
      }
    })
  },
  // 计算地图的高度
  mapheight() {
    let that = this
    wx.getSystemInfo({
      success: (res) => {
        let screenHeight = wx.getSystemInfoSync().windowHeight
        let query = wx.createSelectorQuery().in(this)
        query.select('.top').boundingClientRect()
        query.select('.bot').boundingClientRect()
        query.exec(res => {
          let bgcHeight = res[0].height
          let bgcgrayHeight = res[1].height
          let mapheight = screenHeight - bgcHeight - bgcgrayHeight - 4
          that.setData({
            mapheight: mapheight
          });
        })
      }
    })
  },
  // 手动选择地址
  openMap() {
    let that = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.setStorageSync('sh_oil_user_pre', false)
          wx.navigateTo({
            url: '/pages/nomap/nomap',
          })
        } else { //已授权
          wx.chooseLocation({
            success: function (res) {
              let address = {
                detail: res.address,
                latitude: res.latitude,
                longitude: res.longitude
              }
              wx.setStorageSync('address', address)
            },
            fail(res) {}
          })
        }
      }
    })
  },

  // 移动地图获取中间点经纬度
  regionchange(e) {
    let that = this;
    if (e.type == 'begin' && e.causedBy == "gesture" && that.data.hidden == 1) {
      this.mapCtx = wx.createMapContext('map');
      this.mapCtx.getCenterLocation({
        success(res) {
          const latitude = res.latitude
          const longitude = res.longitude
          that.analysisTap(latitude, longitude)
        }
      })
    }
  },
  // 解析经纬度
  analysisTap(lat, lng) {
    let that = this
    var amapWX = new amapFile.AMapWX({
      key: 'f8b1262c6afbe526f37c449e593ea859'
    });
    amapWX.getRegeo({
      location: lng + ',' + lat,
      success: function (data) {
        that.setData({
          addressDetail: data[0].regeocodeData.formatted_address,
          longitude: data[0].longitude,
          latitude: data[0].latitude
        })
        let address = {
          detail: data[0].regeocodeData.formatted_address,
          latitude: data[0].latitude,
          longitude: data[0].longitude
        }
        wx.setStorageSync('address', address)
      },
      fail: function (info) {}
    })
  },

  // 获取两点间距离及时间
  getDistance() {
    let that = this
    let position1 = {
      lat: that.data.markers[0].latitude,
      lng: that.data.markers[0].longitude,
    }
    let position2 = {
      lat: that.data.markers[1].latitude,
      lng: that.data.markers[1].longitude,
    }
    let s = App.api.$getDistance(position1, position2)
    that.setData({
      'markers[1].callout.content': '待配送\n据我' + s + 'km'
    })
    let hour = (s / 40).toFixed(2)
    var ab_str = hour.toString();
    var ab_num = parseInt(ab_str.substring(0, ab_str.indexOf('.')));
    const s1 = ab_str.replace(/\d+\.(\d*)/, '$1')
    var time = ((s1 / 100) * 60).toFixed(0);
    that.setData({
      hour: ab_num,
      time: time > 0 ? time : 1,
    })
  },
  Rad: function (d) { //根据经纬度判断距离
    return d * Math.PI / 180.0;
  },
  // 拨打电话
  phone(e) {
    App.api.$makePhone(e)
  },

  // 取消订单
  bindPickerChange(e) {
    console.log(e)
    let that = this
    let id = e.currentTarget.dataset.id
    let index=e.detail.value
    that.setData({
      index: e.detail.value
    })
    if (that.data.index != '') {
      App.api.$http({
        url: 'Oilorder/cancel',
        method: 'GET',
        data: {
          order_id: id,
          reason:that.data.array[index]
        }
      }, {}).then(res => {
        if (res) {
          App.api.$showSuccess(res.msg)
          setTimeout(function () {
            that.setData({
              hidden: 1,
              markers: [],
              points: [],
              ask: ''
            })
            that.mapheight()
            wx.setStorageSync('ask', '')
          }, 2000)
        }
      })

    }
  },

  // 我要加油
  oil() {
    let that = this
    let is_support = that.data.is_support
    if (is_support == 0) {
      App.api.$showSuccess('该地区暂未开放')
      return
    }
    let is_enable = that.data.detail.oli_up_down.is_enable || 0
    if (is_support == 1 && is_enable == 0) {
      App.api.$showSuccess('暂不可下单，请稍后再试')
      return
    }
    if (that.data.addressDetail == '') {
      App.api.$showSuccess('请选择地址')
      return
    }
    App.api.$http({
      url: 'Oilorder/submit',
      method: 'POST',
      data: {
        address: that.data.addressDetail,
        longitude: that.data.longitude,
        latitude: that.data.latitude,
        buyer_remark: wx.getStorageSync('ask') || ''
      }
    }, {}).then(res => {
      if (res) {
        App.api.$showSuccess(res.msg)
        wx.setStorageSync('hidden', 2)
        that.setData({
          hidden: 2
        })
        that.order()
        that.mapheight()
      }
    })
  },
  add() {
    let that = this
    wx.chooseLocation({
      success: function (res) {
        App.api.$http({
          url: 'OilOrder/editAddress',
          method: 'POST',
          data: {
            address: res.address,
            latitude: res.latitude,
            longitude: res.longitude,
            order_id: that.data.order.order_id
          }
        }, {}).then(res => {
          App.api.$showSuccess(res.msg)
          that.order()
        })
      },
      fail() {}
    })
  },
  onHide: function () {
    let that = this
    clearInterval(that.data.setInter)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // let that = this
    // clearInterval(that.data.setInter)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})